如何在 HTML Canvas 中缩小 arc/ellipse 的大小
How to shrink the size of arc/ellipse in HTML Canvas
问题
我想在 HTML Canvas 上绘制圆弧,以此来遮盖图像。
我可以画弧线,它有一个展开的动画。
但是,我无法让它缩小或变小......
有什么问题?
Google Chrome 开发工具没有暴露任何错误。
提前致谢。
代码
<canvas id="canvas" width="350" height="184"></canvas>
<script>
var w = 350;
var h = 184;
var c = 0;
window.onload = function () {
draw();
}
function draw() {
var canvas = document.getElementById('canvas');
if(!canvas || !canvas.getContext) return false;
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = "MY_IMAGE.jpg";
img.onload = () => {
setInterval(() => {
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.arc(0, 0, w - c, Math.PI * 2, 0, false); // Doens't work!
// ctx.arc(0, 0, c, Math.PI * 2, 0, false); // Works! But I want to make the arc smaller, not bigger...
ctx.clip();
ctx.drawImage(img, 0, 0, 350, 184);
c += 1;
if(c >= w) {
c = 0;
}
}, 20);
}
}
代码运行良好。它似乎不起作用,因为您没有在重新绘制帧之间清除 canvas。一旦在 canvas 上绘制了某些东西,它就会留在那里。所以图像正在缩小,但你看不到它,因为更大的图像已经绘制并留在屏幕上。
添加ctx.clearRect(0,0,canvas.width,canvas.height)
在绘制图像之前。您也不需要保存和恢复方法。
问题
我想在 HTML Canvas 上绘制圆弧,以此来遮盖图像。
我可以画弧线,它有一个展开的动画。
但是,我无法让它缩小或变小......
有什么问题?
Google Chrome 开发工具没有暴露任何错误。
提前致谢。
代码
<canvas id="canvas" width="350" height="184"></canvas>
<script>
var w = 350;
var h = 184;
var c = 0;
window.onload = function () {
draw();
}
function draw() {
var canvas = document.getElementById('canvas');
if(!canvas || !canvas.getContext) return false;
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = "MY_IMAGE.jpg";
img.onload = () => {
setInterval(() => {
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.arc(0, 0, w - c, Math.PI * 2, 0, false); // Doens't work!
// ctx.arc(0, 0, c, Math.PI * 2, 0, false); // Works! But I want to make the arc smaller, not bigger...
ctx.clip();
ctx.drawImage(img, 0, 0, 350, 184);
c += 1;
if(c >= w) {
c = 0;
}
}, 20);
}
}
代码运行良好。它似乎不起作用,因为您没有在重新绘制帧之间清除 canvas。一旦在 canvas 上绘制了某些东西,它就会留在那里。所以图像正在缩小,但你看不到它,因为更大的图像已经绘制并留在屏幕上。
添加ctx.clearRect(0,0,canvas.width,canvas.height)
在绘制图像之前。您也不需要保存和恢复方法。