首页 > 解决方案 > 在 Java Script 中将图像添加到按钮中

问题描述

我需要使图像可点击(按钮)或将图像添加到按钮。

这是我要修改的代码

class Button{
    constructor(){
      this.button1 = createButton("Test");
      }
 
    display(){
      this.button1.position(displayWidth - 1150, displayHeight/2 - 300);
      this.button1.size(125.6,183.3);
      }
    
    this.button1.mousePressed(()=>{
      console.log("Worked!!");
  });

我正在使用 Visual Studio 代码,我有 p5 play 和 p5.js 库。

先感谢您。

标签: javascriptvisual-studio-codep5.js

解决方案


您可以通过设置 css 样式属性style()。例如设置“背景”属性:

button.style('background', "url(https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/apple64.png)");

let button;
function setup() {
    createCanvas(100, 100);
    background(0);
    button = createButton("Test");
    button.style('color', "white");
    button.style('background', "url(https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/apple64.png)");
    button.style('width', "64px");
    button.style('height', "64px");
    button.position(19, 19);
    button.mousePressed(buttonPressed);
}

function buttonPressed() {
    button.style('background', "url(https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/banana64.png)");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>


推荐阅读