简体   繁体   English

如何多次引用我的html5画布绘图?

[英]How to refer to me html5 canvas drawing more than once?

I've created a drawing using canvas which I intend to use multiple times for various navigation links, my problem is that when I refer to it more than once it will only show 1. Obviously I could duplicate the code for each instance but I plan on using this quite a lot so this is not ideal. 我已经使用画布创建了一个图形,打算将其多次用于各种导航链接,但是我的问题是,当我多次引用它时,它只会显示1。显然,我可以为每个实例复制代码,但是我计划大量使用,因此并不理想。 Please have a look at the code below and the linked jsfiddle. 请查看下面的代码和链接的jsfiddle。 Many thanks. 非常感谢。

http://jsfiddle.net/LTu2H/ http://jsfiddle.net/LTu2H/

//first reference
<canvas id="canvasId" width="50" height="50"></canvas>
//second reference 
<canvas id="canvasId" width="50" height="50"></canvas>

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

var width = 125;  // Triangle Width
var height = 45; // Triangle Height
var padding = 5;

// Draw a path
context.beginPath();
context.moveTo(padding + width-125, height + padding);        // Top Corner
context.lineTo(padding + width-90,height-17 + padding); // point
context.lineTo(padding, height-35 + padding);         // Bottom Left
context.closePath();

// Fill the path
context.fillStyle = "#9ea7b8";
context.fill();
</script>

You can only have unique ID's 您只能拥有唯一的ID


HTML: HTML:

<canvas id="canvasId" width="50" height="50"></canvas>
<canvas id="canvasId2" width="50" height="50"></canvas>

JS: JS:

function drawSomething(canvas) {
    var context = canvas.getContext("2d");

    var width = 125;  // Triangle Width
    var height = 45; // Triangle Height
    var padding = 5;

    // Draw a path
    context.beginPath();
    context.moveTo(padding + width-125, height + padding);        // Top Corner
    context.lineTo(padding + width-90,height-17 + padding); // point
    context.lineTo(padding, height-35 + padding);         // Bottom Left
    context.closePath();

    // Fill the path
    context.fillStyle = "#9ea7b8";
    context.fill();

}

drawSomething(document.getElementById("canvasId"));
drawSomething(document.getElementById("canvasId2"));

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

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