javascript - clearRect 后 Canvas 移动阴影

标签 javascript html canvas

我是 HTML5 新手,开始学习 Canvas 。

目前,我正在使用 Canvas 使一些对象旋转。我创建的矩形确实会移动,但是,我遇到了一个问题,在对象移动后,一些阴影仍然存在,正如您从我捕获的图像中看到的那样。

enter image description here

我只想要矩形,不包括蓝色背景笨拙的东西。我尝试使用不同的浏览器来查看此 HTML5 文档,但出现了同样的问题。是我电脑的问题,还是代码的问题?如果是这样,我该如何解决?

我还在 jsFiddle 中附上了旋转矩形示例的源代码:http://jsfiddle.net/hphchan/ogoj9odf/1/

这是我的关键代码:

在 JavaScript 中:

function canvaScript() {
    var canvas = document.getElementById('myCanvas'); 
    var context = canvas.getContext('2d'); 

    context.translate(200, 200); // fix the origin as center of the canvas
    rotating(context); 
}

function rotating(context) {
    context.clearRect(-50, -100, 100, 200); // why boundaries, shadows exist??
    context.rotate(Math.PI/180); 
    context.fillStyle = '#0000FF'; 
    context.fillRect(-50, -100, 100, 200); 

    setTimeout(function() {rotating(context)}, 100); 
}

在 HTML 中

<body onload="canvaScript()">
    <canvas id="myCanvas" width="400" height="400"></canvas>  
</body>

感谢您的回答。

最佳答案

这个问题可能来自抗锯齿。

画完旋转后直接清除就可以看到了:

function canvaScript() {
    var context = canvas.getContext('2d'); 

    context.translate(200, 200); // fix the origin as center of the canvas
    context.rotate(Math.PI/4);
    rotating(context); 
}

function rotating(context) {
    context.fillStyle = '#0000FF'; 
    context.fillRect(-50, -100, 100, 200); 
	context.clearRect(-50, -100, 100, 200); 
}

canvaScript(); 
<canvas id="canvas" width="400" height="400"></canvas>

因此解决此问题的一种解决方案是清除比您刚刚绘制的矩形稍大的 clearRect

function canvaScript() {
    var context = canvas.getContext('2d'); 

    context.translate(200, 200); // fix the origin as center of the canvas
    rotating(context); 
}

function rotating(context) {
    // clear one extra pixel in all directions
    context.clearRect(-51, -101, 102, 202); 
    context.rotate(Math.PI/180); 
    context.fillStyle = '#0000FF'; 
    context.fillRect(-50, -100, 100, 200); 

    setTimeout(function() {rotating(context)}, 100); 
}

canvaScript(); 
<canvas id="canvas" width="400" height="400"></canvas>

关于javascript - clearRect 后 Canvas 移动阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32772127/

相关文章:

javascript - 页面刷新 jsp 后选择框选项保持选中状态

jquery - 如何绘制具有透明度的png图像轮廓(边框)

php - 如何将 html 和 css 转换为图像?

html - Blender 导出到 Three.js

javascript - 我如何突出显示 n 个序列字符串单词

javascript - 如何在不重新创建 map 的情况下使用 Knockout.js 切换 KML 图层?

javascript - 在 View 中从 textarea 加载内容

html-css奇怪的行序

javascript - 在用 javascript 和 html 构建的网格中,如何为网格中满足条件的所有单元格分配新的文本节点值

javascript - 将 javascript 生成的图像复制到剪贴板