检查此JavaScript制作模因

时间:2018-09-04 21:37:28

标签: javascript html html5-canvas

下面是我编写的HTML代码。实际上,问题是当我在调用get()onclick函数时,浏览器中没有任何更改。但是,在“提交”按钮上单击多次后,显示的外观会​​立即发生变化,这是我想要的,但是持续时间非常短(例如0.1秒)。

var t = "top Text here";
var b = "bottom Text";
var i = "https://images.pexels.com/photos/1385326/pexels-photo-1385326.jpeg";
console.log(t, b, i);
memeCanvas();


function get() {
  t = document.getElementById("topText").value;
  b = document.getElementById("botText").value;
  i = document.getElementById("imgLink").value;
  console.log(t, b, i);
  memeCanvas();
}

function memeCanvas() {
  var c = document.querySelector("#c");
  var ctx = c.getContext("2d");
  var image = new Image();

  image.onload = function() {
    console.log("Image Loaded");

    ctx.drawImage(image, 0, 0, 400, 400);

    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, 400, 50);
    ctx.fillRect(0, 350, 400, 50);
    ctx.strokeText(t, 10, 10);

    ctx.strokeStyle = "Black";
    ctx.strokeRect(0, 0, 400, 50);
    ctx.strokeRect(0, 350, 400, 50);
    ctx.strokeText(b, 0, 370);
  }
  image.src = i;
}
canvas {}
<body>

  <canvas id="c" width="400" height="400"></canvas>
  <form>
    <input type="text" id="topText" value="hahaha">
    <input type="text" id="botText" value="nooo">
    <input type="text" id="imgLink" value="chicken.jpg">
    <!--*here chick.jpeg is an image stored in my computer */-->
    <input type="submit" onclick="get()">
  </form>
</body>

1 个答案:

答案 0 :(得分:0)

将您的<form>更改为<div>即可解决您的问题。

还要确保此示例的imgLink上有有效的图像,我会更改值,以便您可以实际看到它

var t = "top Text here";
var b = "bottom Text";
var i = "https://images.pexels.com/photos/1385326/pexels-photo-1385326.jpeg";

var c = document.querySelector("#c");
var ctx = c.getContext("2d");
memeCanvas();

function get() {
  t = document.getElementById("topText").value;
  b = document.getElementById("botText").value;
  i = document.getElementById("imgLink").value;
  memeCanvas();
}

function memeCanvas() {
  var image = new Image();
  image.onload = function() {

    ctx.drawImage(image, 0, 0, 400, 400);

    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, 400, 50);
    ctx.fillRect(0, 350, 400, 50);
    ctx.strokeText(t, 10, 10);

    ctx.strokeStyle = "Black";
    ctx.strokeRect(0, 0, 400, 50);
    ctx.strokeRect(0, 350, 400, 50);
    ctx.strokeText(b, 0, 370);
  }
  image.src = i;
}
<body>

  <div>
    <input type="text" id="topText" value="hahaha">
    <input type="text" id="botText" value="nooo">
    <input type="text" id="imgLink" value="https://presspack.rte.ie/wp-content/blogs.dir/2/files/2015/04/AMC_TWD_Maggie_Portraits_4817_V1.jpg">
    <input type="submit" onclick="get()">
  </div>

  <canvas id="c" width="400" height="400"></canvas>
</body>