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

Possible to draw on Multiple Canvas by ClassName?

本文关键字:绘制 ClassName 可以通过      更新时间:2023-09-26

从下面的代码中,我将值传递到函数中,并使用它们来绘制特定的形状。然而,当我尝试通过ClassName获取canvas时,我的代码中断了,它说.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();
 }

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