可以通过 ClassName 绘制 Multiple Canvas 吗?

Possible to draw on Multiple Canvas by ClassName?

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

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();
 }

document.getElementsByClassName() returns 一个 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();
   }
 }