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

查看:12
本文介绍了所有 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天全站免登陆