简体   繁体   中英

One javascript function from multiple html buttons

Weird question but I have a javascript function that draws on a canvas. I created buttons on HTML that uses that function. 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. I tried giving the button ids but you shouldn't have multiple ids. I tried using classes but it didn't seem to work. Using AngularJS.

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

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.

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. This way you code will be clean and maintainable as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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