HTML canvas fill difference on Firefox vs Chrome

依然范特西╮ 提交于 2019-12-11 00:03:51

问题


Consider the snippet below - available on jsFiddle: http://jsfiddle.net/Xqu5U/2/

ctx = document.getElementById('canvas').getContext('2d');
ctx.beginPath();
ctx.fillStyle = '#FF0000';

for (var i = 0; i < 20; i++) {
    ctx.arc(i * 10, 50 + Math.sin(i * 0.5) * 15, 2, 0, Math.PI * 2);
}

ctx.fill();

It works as expected on Google Chrome, but Firefox renders a fill from the last arc to the first one. How can the snippet above be updated to get Firefox drawing the arcs exactly like Chrome?


回答1:


I found a way to get it working: http://jsfiddle.net/Xqu5U/3/. Basically just add ctx.closePath() inside the for loop. Not sure if this is the best solution though...




回答2:


I know this is old question but for the future reference:

ctx = document.getElementById('canvas').getContext('2d');
ctx.beginPath()
ctx.fillStyle = '#FF0000'

for (var i = 0; i < 20; i++) {
    ctx.arc(i * 10, 50 + Math.sin(i * 0.5) * 15, 2, 0, Math.PI * 2)
    ctx.closePath()
}

ctx.fill()



回答3:


It's really old, but someone just pointed me to here.

The problem was a chrome bug (now fixed since an undetermined long time). FF behavior was correct.

arc() method doesn't include a moveTo(x, y) call, but a lineTo one.

So in order to get your desired result, you just have to call ctx.moveTo(nextCX + radius, nextCY) where nextCX and nextCY are the center x and y coordinates of your next arc to be drawn. We add radius to the x position because, when the arc's starting angle is set to 0, the arc is being drawn from 3 o'clock, without this + radius, we would still have an internal lineTo(cx + radius, cy) being added, visible when calling stroke().

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

ctx.beginPath();
ctx.fillStyle = '#FF0000';
for (var i = 0; i < 20; i++) {
    // you need to moveTo manually.
    ctx.moveTo(i * 10 + 2, 50 + Math.sin(i * 0.5) * 15)
    ctx.arc(i * 10, 50 + Math.sin(i * 0.5) * 15, 2, 0, Math.PI * 2);
}
ctx.fill();
<canvas id="canvas"></canvas>



回答4:


You don't have really something to do about it...

It's the way both browser's work...

You can always design it with CSS with the right commands to make it the same...

Go to http://w3schools.com and find what you need for doing that :)

Good luck !



来源:https://stackoverflow.com/questions/14060495/html-canvas-fill-difference-on-firefox-vs-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!