所有html画布形状都被赋予了最后添加的对象的颜色 [英] All html canvas shapes are given the color of the last object added

查看:62
本文介绍了所有html画布形状都被赋予了最后添加的对象的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个奥林匹克类型的标志,纯粹是为了学习如何绘制JavaScript。这应该画出两个圆圈-一个蓝色,一个黑色...
这是代码(我很抱歉,正在两个函数之间移动东西-不知道如何非明确地引用上下文):

I was trying to do an Olympic type flag, purely as a way of learning how to draw in JavaScript. This should draw two circles - one blue, one black... Here is the code (which I apologise for, been moving things between the two functions - Not sure how to refer to the context non-explicitly):

function drawCircle(ctx,x,y,radius, color){
  var startAngle = 0;
  var endAngle = (Math.PI*2);
  var clockwise = true;
  ctx.fillStyle = color;
  ctx.arc(x,y,radius,startAngle,endAngle, clockwise);
  ctx.fill();
  ctx.closePath;
}
function drawCircles(){
    var canvas = document.getElementById('myCanvasArea');  
    var ctx = canvas.getContext('2d'); 
     if (canvas.getContext){    
        drawCircle(ctx,50,25,25, 'blue');
        drawCircle(ctx,100,25,25, 'black');
    }
}

我得到两个黑色圆圈。我想我没有区分这两种形状,因此第二个的属性应用于第一个。

I get two black circles. I presume I'm not differentiating between the two shapes, therefore the properties of the 2nd are applied to the 1st.

如何区分?我当时想让每个人点击都会引发一个动作。我是从一开始就搞错了吗?

How do I make that distinction? I was thinking of making clicking each one raise an action. Am I going about this incorrectly from the start?

推荐答案

这是因为您从未调用过 beginPath()

It's because you are never calling beginPath()!

function drawCircle(ctx,x,y,radius, color){
  var startAngle = 0;
  var endAngle = (Math.PI*2);
  var clockwise = true;
  ctx.fillStyle = color;
  ctx.beginPath(); // <-- Need me!!
  ctx.arc(x,y,radius,startAngle,endAngle, clockwise);
  ctx.fill();
  ctx.closePath;
}

由于您未调用beginPath,因此将绘制一个蓝色圆圈,然后您正在继续一条路径,该路径现在有两个圆圈(旧的和新的一个),并以黑色绘制该路径(因此两个圆圈)!

Since you don't call beginPath, you are drawing one blue circle, then you are continuing a path that now has two circles (the old one and the new one), and drawing that path (and thus both circles) black!

相反,您想绘制一个蓝色圆圈,将其填充为蓝色,开始一条新路径,然后绘制一个黑色圆圈。

Instead you want to draw one blue circle, fill it blue, begin a new path, and draw that one black.

实时代码:

http://jsfiddle.net/ 5PDUb / 1 /

这篇关于所有html画布形状都被赋予了最后添加的对象的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆