Html5画布和jquery [英] Html5 canvas and jquery

查看:191
本文介绍了Html5画布和jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用画布创建了一个三角形,但我想知道是否有办法在mouseover上更改fillStyle颜色,就像它是div和jquery一样。

I have created a triangle using canvas but i was wondering if there was a way to change the fillStyle color on mouseover as if it were a div and jquery.

var context = document.getElementById("canvasId").getContext("2d");

var width = 150; 

var height = 105; 


context.beginPath();
context.moveTo(75, 0);       
context.lineTo(150, 105); 
context.lineTo(0, 105);       
context.closePath();


context.fillStyle = "#ffc821";
context.fill();

感谢您的支持

推荐答案

您可以执行之类的操作。

You can do something like this.

我所做的是将上面的代码放入一个函数中,并添加了一个

What I've done is put the above code into a function, and added a

context.clearRect(0,0,width,height);

将删除旧三角形。从那里我用

which will erase the old triangle. From there I put in a hover for it with the

$('#canvasId').hover(functionIn,functionOut);

表示法。

更新:另外,作为旁注,您可以创建一个三角形这样使用CSS 。这是一个示例,顶部是画布,底部是CSS。

Update: Also, as a side note, you could create a triangle like this using CSS. Here is an example with the canvas one on the top, and CSS one on the bottom.

更新2: 这是新的示例代码。 @puk是对的,我的代码并不关心三角形本身上的悬停,但更多关于canvas元素。但正如您在示例中列出的那样,您需要一个带三角形的分层效果,以便每个部分都不同。不确定您是否希望每个部分单独突出显示,但如果您这样做,示例代码将再次包含< div> < canvas> 示例。由于浏览器不知道画布中的元素,因此您需要跟踪它。 < div> 示例总体来说可能会更快,并且让浏览器处理很多混乱的细节,但是有更复杂的CSS和悬停工作有点出乎意料地在边缘(有些区域不是三角形,会触发悬停)。 < canvas> 示例是一个更复杂的JS代码,可能会慢一点,但可能是预期的行为。

Update 2: Here is new sample code. @puk is right, my code was not concerned about hover on the triangle itself, but more on the canvas element. But as you listed in your example, you wanted a layered effect with a triangle so that each piece is different. Not sure if you want each piece to highlight individually, but if you do, the example code again contains both a <div> and a <canvas> example. Since an 'element' within the canvas is not known by the browser, you would need to keep track of it. The <div> example will likely be faster overall, and lets the browser handle a lot of the messy details, but has more complicated CSS and hover works a little unexpectedly on the edges (there is areas that are not triangle that will trigger hover). The <canvas> example is a lot more complicated JS code, and might be a little slower, but has what is likely the exact expected behavior.

这篇关于Html5画布和jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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