I am participating in the Mid-Autumn Festival Creative Submission contest, please see: Mid-Autumn Festival Creative Submission Contest for details

Mid-Autumn Festival is coming soon, the moon cakes are usually engraved with words or patterns, so if you receive moon cakes, engraved with your own name, is not very surprised? Now let’s use canvas to create your own mooncake!!

Let’s take a look at some renderings

Realize the principle of

The implementation principle is very simple, except for the production date and the text of the moon cake, the other part is a background picture. All we have to do is fill the middle of the moon cake with text messages.

Code implementation

The page effect after code implementation:

First of all, we have an input box on the page, input the text, click OK to render the text information to canvas. There is also a button to download and save. Limit input to 1,2 and 4 characters for typographical beauty.

The relevant code

HTML:

<canvas id="myCanvas" width="400" height="300" style="border:1px solid #d3d3d3;" ></canvas> <input placeholder=" max-width: 100%; color: RGB (50, 50, 50); </button> <button ID ='download'> </button>Copy the code

js:

var input = document.querySelector('#input') var downloadBtn = document.querySelector('#download') input.addEventListener('change', (e) => { processText(e.target.value) }) var canvas = document.getElementById("myCanvas") var ctx = canvas.getContext("2d") downloadBtn.addEventListener('click', SaveImg) var img = new Image() img.src = './images/mooncake.png' Var fontSize = 36 img.onload = function () {drawBackground() processText()} var date = new date () var [y m, d] = [date.getFullYear(), date.getMonth() + 1, date.getDate()] var dateStr = `${y}/${m < 10 ? '0' + m : m}/${d < 10 ? '0' + d : d}` function _fixType(type) { type = type.toLowerCase().replace(/jpg/i, 'jpeg'); var r = type.match(/png|jpeg|bmp|gif/)[0]; return 'image/' + r; }; Function processText(text = 'love ') {var textNum = text.length if (! [1, 2, 4]. Includes (textNum)) {return alert(' 1, 2, 4 '). ') } switch (textNum) { case 1: fontSize = 68 var textY = canvas.height / 2 + 24 draw(text, textY) break case 2: fontSize = 42 var textY = canvas.height / 2 + 14 draw(text, textY) break default: fontSize = 32 var textY = canvas.height / 2 - 6 draw(text.substring(0, 2), Var textY2 = canvas.height / 2 + 30 drawText(tex. substring(2, 4), textY2)}} function draw(text = 'happy ', textY) { ctx.clearRect(0, 0, canvas.width, canvas.height) drawBackground() drawText(text, Function drawDate() {ctx.fillstyle = '#000' ctx.font = '14px KaiTi' ctx.filltext (dateStr, Function drawBackground() {ctx.drawImage(img, 0, 0, 400, 300)} function drawBackground() {ctx.drawImage(img, 0, 0, 400, 300)} textY) { ctx.font = `${fontSize}px KaiTi` var textWidth = ctx.measureText(text).width ctx.strokeStyle = '#bf814b' ctx.shadowOffsetX = 1 ctx.shadowOffsety = 1 ctx.shadowColor = '#000' ctx.shadowBlur = 2 ctx.strokeText(text, 200 - textWidth / 2, textY); ctx.shadowOffsetX = -1 ctx.shadowOffsety = -1 ctx.shadowColor = '#e0b64c' ctx.shadowBlur = 1 ctx.fillStyle = '#bf814b' ctx.fillText(text, 200 - textWidth / 2, textY); Function saveImg() {var canvas = document.getelementById ("myCanvas") var image = new image (); var imgData = canvas.toDataURL({ format: 'image/png', quality: 1, width: 800, height: 600 }); var url = imgData.replace(_fixType('png'), 'image/octet-stream'); var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = imgData; save_link.download = 'mooncake.png'; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event); }Copy the code

The above is a complete JS logic implementation, the code should be relatively easy to read and understand.

What is worth mentioning here is, how do we achieve the 3D effect that the text in the moon cake highlights? CSS can be implemented with text-shadow property, while Canvas has corresponding API to achieve:

  • ShadowOffsetX: horizontal offset
  • ShadowOffsetY: vertical offset
  • I don’t see a blur
  • ShadowColor: shadowColor

See the drawText method for more details, but it is important to note that to make the text stand out in 3D, the text color must be the same as the background color, and the shadow color can be fine-tuned.

Something worth mentioning

If you open the HTML code directly in your browser, you will get an error when you click the download button

We need to request the way to open it, the method is very simple. Vs Code search to install the Live Server plug-in, click on Leve Server to enable service access.

Related references

The raised and sunken effect of the text

Canvas generates pictures and saves them locally