简体   繁体   English

单击鼠标更改画布元素属性

[英]Change canvas element properties on mouse click

Please see this Fiddle: https://jsfiddle.net/1gb9a2x3/ . 请参阅此提琴: https : //jsfiddle.net/1gb9a2x3/

I have a full-screen HTML5 canvas element with some blocks moving a bit random. 我有一个全屏HTML5画布元素,其中一些块随机移动。 It is a nice effect, which I will tweak later, but what I am trying to do now is change some properties on user input of an individual or multiple elements. 这是一个很好的效果,我稍后将对其进行调整,但是现在我要尝试的是更改单个或多个元素的用户输入上的某些属性。 So, when the user clicks a button somewhere, change color, move it, hide it, and so on. 因此,当用户单击某处的按钮时,更改颜色,移动它,隐藏它,等等。 I tried to manipulate the update function on the fly , but unfortunately no luck at all. 我试图即时操作update功能,但不幸的是根本没有运气。 In the example is currently no code which covers user input, just because nothing I tried seems to work, because of scoping-problems, the limits of canvas-element or other. 在该示例中,当前没有代码涵盖用户输入,只是因为范围问题,画布元素或其他元素的限制,我尝试过的任何事情似乎都不起作用。

I tried to use jQuery for that, by the way. 顺便说一下,我试图为此使用jQuery。 So my question is: is there a way to do a simple piece of jQuery-code like: 所以我的问题是:有没有一种方法可以像这样简单地编写jQuery代码:

$('button').click(function() {
   Item[0].width = 10;
   update();
});

Any suggestions to get me started are more than welcome. 任何使我入门的建议都值得欢迎。 Thank you! 谢谢!

I couldn't get my code to work because I couldn't see the errors, but what you can do is declare some kind of array with predefined colors in it, like 我无法使我的代码正常工作,因为我看不到错误,但是您可以做的是声明一种带有预定义颜色的数组,例如

fillColors = ["rgba(255,150, 0,","rgba(255, 255, 255,"];

Then in the canvas onclick, do a for loop that sets the 'circles' color to the one next in the array. 然后在onclick画布上,执行for循环,将“圆圈”颜色设置为数组中的下一个。 (Also, make sure to give the items object a color property, and use ctx.fillStyle = this.color; in the update function so this works) (此外,请确保为items对象提供color属性,并在更新函数中使用ctx.fillStyle = this.color;这样可以正常工作)

canvas.onclick = function(){
    for(var i = 0; i < circles.length; i++){
        circles[i].color = fillColors[0] + circles[i].opacity + ')';
        // first output is "rgba(255,150, 0, opacity)"
    }
    //then move the color to the end of the array
    var color1 = fillColors[0];
    fillColors.splice(0, 1);
    fillColors.push(color1);
}

I hope I've helped and good luck! 希望我有所帮助,祝你好运!

Your code is almost correct just change it to the following and add a button 您的代码几乎是正确的,只需将其更改为以下内容并添加一个按钮

$('button').click(function() {
   circles[1].size = Math.random() * 1000;
   // no need for update since it is updated by function draw();
});

it will randomly set a size of circles 1 它将随机设置圆圈的大小1

you can check it here https://jsfiddle.net/xbjjrroy/ 您可以在这里检查它https://jsfiddle.net/xbjjrroy/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM