【问题标题】:Canvas draw an image in circular increments?画布以圆形增量绘制图像?
【发布时间】:2023-04-03 04:39:01
【问题描述】:

我想以圆形(或类似的)增量绘制一个图像作为进度条,我原本想在画布上用线条绘制它,但最终对它的外观不满意。

这个 jsfiddle 展示了我希望它如何查看 100%,在 0% 时不会绘制任何条,还标记了条的起点和终点。

var canvas = document.getElementById("test");
var ctx = canvas.getContext("2d");

var img = new Image();
img.src = "http://i.imgur.com/Jhteqyx.png";

img.onload = function() {

  ctx.drawImage(img,
    0,
    0
  );
};


//game score and level number dont draw over or clear
ctx.font = 'bold 50px Arial';
ctx.fillText("LVL NUMBER", 45, 100);
ctx.fillText(" TOTAL SCORE", 15, 190);

//label only ignore
ctx.font = 'bold 10px Arial';
ctx.fillText("end", 57, 25);
ctx.fillText("start", 125, 25);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="test" width=700 height=700></canvas>

我认为这可以使用额外的 drawImage 参数来实现,我已经在使用它来绘制倒数计时器,使用图像作为填充,但我不确定如何以圆形方式绘制并增加复杂性忽略中间区域?

 context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

这可能是解决问题的错误方法,这可能吗?

【问题讨论】:

    标签: html canvas drawimage


    【解决方案1】:

    您可以使用剪切路径逐步隐藏/显示您的边框图像。

    这是伪代码:

    // save the context state and beginPath
    ctx.save();
    ctx.beginPath();
    
    // draw your clipping path here
    // The clipping path will include whatever part of the image you want visible
    
    // set your path as a clipping path
    ctx.clip();
    
    // draw your border image
    // only the clipping path portion of the border image will be visible
    ctx.drawImage(img,0,0);
    
    // restore the context
    // this turns the clipping off
    ctx.restore();
    
    
    // now draw your level and score (clipping is no longer in effect)
    
    //game score and level number dont draw over or clear
    ctx.font = 'bold 50px Arial';
    ctx.fillText("LVL NUMBER", 45, 100);
    ctx.fillText(" TOTAL SCORE", 15, 190);
    
    //label only ignore
    ctx.font = 'bold 10px Arial';
    ctx.fillText("end", 57, 25);
    ctx.fillText("start", 125, 25);
    

    【讨论】:

    • 再次感谢,单行可以剪辑图像还是必须是封闭的形状?你昨天给我的例子画了一条剪切线(?)而不是一条彩色线,非常适合这项任务。
    • 不,线条不能是剪切路径。如果您想使用我之前的示例进行剪切,只需将直线替换为矩形,将弧替换为楔形即可。
    • 谢谢,现在试试。我想你不能告诉我这些矩形做错了什么?我将它分成 2 个函数,一个用于垂直,另一个用于水平,并保持第一个的 y 坐标和后者的 x 相同。 jsfiddle.net/P2qTq/1
    • 对于水平线,改变宽度。对于垂直线,改变高度。对于角落,绘制楔形 - 具有闭合路径的弧(弧需要延伸到您尝试剪切的边框之外。如果您的边框下除了纯色背景之外还有其他东西,您将需要使用这种剪切方法而不是“用反转线显示”方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2013-11-25
    • 2014-09-16
    相关资源
    最近更新 更多