canva绘制海报02: 圆角海报

接上篇, 地址

需求更新:

绘制的海报要求有圆角,其他设置一如既往

技术思路

  1. 画圆角矩形,然后裁剪此为画布区域
  2. 在上一画布区域进行绘制图片,即可
  3. 其他照常

涉及API

Canvas.MoveTo, .lineTo, .arc, .drawImage, .clip

// 画布,图片获取等
    const canvas = document.getElementById('canvas')
    const context = canvas.getContext('2d')
    const img = document.getElementById('img')
    img.onload = ()=>{
        // 绘制圆角矩形
        drawRoundedRect(context, 0, 0, canvas.width, canvas.height, 14);
        // 画布裁切
        context.clip()
        // 海报绘制到裁切后的画布上
        context.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0,canvas.width, canvas.height);
        // 导出画布为图片
        document.getElementById("canvas_img").src = canvas.toDataURL('image/png')
    }
    // 绘制圆角矩形
    function drawRoundedRect (ctx, x, y, width, height, radius) {
      ctx.moveTo(x + radius, y)
      ctx.lineTo(x + width - radius, y)
      ctx.arc(x + width - radius, y + radius, radius, 1.5 * Math.PI, 2 * Math.PI)
      ctx.lineTo(x + width, y + height - radius)
      ctx.arc(x + width - radius, y + height - radius, radius, 0, 0.5 * Math.PI)
      ctx.lineTo(x + radius, y + height)
      ctx.arc(x + radius, y + height - radius, radius, 0.5 * Math.PI, 1 * Math.PI)
      ctx.lineTo(x, y + radius)
      ctx.arc(x + radius, y + radius, radius, 1 * Math.PI, 1.5 * Math.PI)
    }

效果图如下

image

Tips:

  1. canvas.toDataURL时候类型请选择为 image/png,而非其他类型,否则会出现四个黑色角
  2. 解决清晰度问题,请参考上一篇文章

本示例完整代码地址: 传送门

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。