[英]One javascript function from multiple html buttons
Weird question but I have a javascript function that draws on a canvas. 奇怪的问题,但我有一个在画布上绘制的javascript函数。 I created buttons on HTML that uses that function.
我在使用该功能的HTML上创建了按钮。 I have multiple buttons with different image sources that I want to use for that one function without having repeat the function many times and just change the imgsrc.
我有多个按钮,这些按钮具有不同的图像源,我想将其用于该功能,而无需多次重复该功能,而只需更改imgsrc。 I tried giving the button ids but you shouldn't have multiple ids.
我尝试提供按钮ID,但您不应有多个ID。 I tried using classes but it didn't seem to work.
我尝试使用类,但是似乎没有用。 Using AngularJS.
使用AngularJS。
HTML HTML
<md-button onclick="(new avatarCanvas()).body()" style="border: 3px solid black;"><input class="image" value="www.website.com/image1.png" type="hidden"></md-button>
<md-button onclick="(new avatarCanvas()).hair()" style="border: 3px solid black;"><input class="hair" value="www.website.com/image2.png" type="hidden"></md-button>
<md-button onclick="(new avatarCanvas()).hair()" style="border: 3px solid black;"><input class="hair" value="www.website.com/image3.png" type="hidden"></md-button>
<md-button onclick="(new avatarCanvas()).hair()" style="border: 3px solid black;"><input class="hair" value="www.website.com/image4.png" type="hidden"></md-button>
<md-button onclick="(new avatarCanvas()).hair()" style="border: 3px solid black;"><input class="hair" value="www.website.com/image5.png" type="hidden"></md-button>
JavaScript JavaScript的
var canvas1 = document.getElementById('layer1');
var ctx1 = canvas1.getContext('2d');
var canvas2 = document.getElementById('layer2');
var ctx2 = canvas2.getContext('2d');
var imageObj = new Image();
this.body = function() {
imageObj.onload = function() {
ctx1.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height);
};
imageObj.src = document.getElementsByClassName("image").value;
}
this.hair = function() {
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
imageObj.onload = function() {
ctx2.drawImage(imageObj, 64.43, 7, imageObj.width, imageObj.height);
};
imageObj.src = document.getElementsByClassName("hair").value;
}
I would suggest to you to create custom directive on button to handle the click event as it is repeated task. 我建议您在按钮上创建自定义指令,以处理单击事件,因为它是重复任务。 And you can add custom attributes like "data-img-path" rather using hidden variable to pass the image path.
您可以添加自定义属性,例如“ data-img-path”,而无需使用隐藏变量来传递图像路径。
eg: 例如:
<md-button data-load-avatar style="border: 3px solid black;" data-image-path="www.website.com/image1.png" />
here "data-load-avatar" is a custom directive where you can add click event and read the attribute "data-image-path" and use this image path in load that in canvas. 这里的“ data-load-avatar”是一个自定义指令,您可以在其中添加click事件并读取属性“ data-image-path”,并在加载画布时使用此图像路径。 This way you code will be clean and maintainable as well.
这样,您的代码也将很干净且可维护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.