可以通过ClassName在多个画布上绘制?

时间:2016-05-06 09:05:14

标签: javascript canvas getelementsbyclassname

从下面的代码中我将值传递给我的函数,并使用它们来绘制我的特定形状。但是,当我尝试通过ClassName获取画布时,我的代码中断并且它表示.getContext()不是函数。所以我在这里试图找到一种方法。使用我当前的配置,我不相信传递实际的文档画布对象是可能的。

function drawShape1(topWidth, shadeHeight) {
   var canvas = document.getElementById('product-render-configurator');
   var paper  = canvas.getContext('2d');

   paper.clearRect(0, 0, canvas.width, canvas.height);

   // begin custom shape
   paper.beginPath();
   //draw Shade String
   paper.moveTo(150, 0);
   paper.lineTo(150, 38);
   //draw shadeTop
   paper.moveTo( ( canvas.width / 2 ) - topWidth, 40 );
   paper.quadraticCurveTo( 150 , 35, ( canvas.width / 2 ) + topWidth, 40);
   paper.lineTo( ( canvas.width / 2 ) + topWidth, shadeHeight );
   paper.quadraticCurveTo( canvas.width / 2 , shadeHeight - 5, ( canvas.width / 2 ) - topWidth, shadeHeight);
   paper.lineTo( ( canvas.width / 2 ) - topWidth, 40 );
   paper.moveTo( (canvas.width / 2) - topWidth, shadeHeight );
   paper.quadraticCurveTo( canvas.width / 2 , shadeHeight + 5, ( canvas.width / 2 ) + topWidth, shadeHeight);

   // complete custom shape

   paper.lineWidth = 0.5;
   paper.strokeStyle = 'black';
   paper.stroke();
 }

1 个答案:

答案 0 :(得分:0)

enter image description here返回一个HTMLCollection(一个类似数组的对象),因此您无法直接在其上调用.getContext()。您必须遍历其元素并直接在每个元素上调用.getContext()

function drawShape1(topWidth, shadeHeight) {
   var canvases = Array.from(document.getElementsByClassName('class-name'));
   for (let canvas of canvases) {
     var paper  = canvas.getContext('2d');

     paper.clearRect(0, 0, canvas.width, canvas.height);

     // begin custom shape
     paper.beginPath();
     //draw Shade String
     paper.moveTo(150, 0);
     paper.lineTo(150, 38);
     //draw shadeTop
     paper.moveTo( ( canvas.width / 2 ) - topWidth, 40 );
     paper.quadraticCurveTo( 150 , 35, ( canvas.width / 2 ) + topWidth, 40);
     paper.lineTo( ( canvas.width / 2 ) + topWidth, shadeHeight );
     paper.quadraticCurveTo( canvas.width / 2 , shadeHeight - 5, ( canvas.width / 2 ) - topWidth, shadeHeight);
     paper.lineTo( ( canvas.width / 2 ) - topWidth, 40 );
     paper.moveTo( (canvas.width / 2) - topWidth, shadeHeight );
     paper.quadraticCurveTo( canvas.width / 2 , shadeHeight + 5, ( canvas.width / 2 ) + topWidth, shadeHeight);

     // complete custom shape

     paper.lineWidth = 0.5;
     paper.strokeStyle = 'black';
     paper.stroke();
   }
 }