Categories for Presents


My first canvas and javascript post. I had to do some research on how to make this work. It wasn’t that hard. I already use a plugin to remove the p-tag wordpress inserts. jQuery is used on the site. The script itself is easy.

The first function setCanvas sets the size of the canvas element. There is no way to do this with css, as far as i know.

function setCanvas() {
	var viewportwidth;
	var viewportheight;

	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerWidth,
		viewportheight = window.innerHeight

	//set width and height to 80% of total width
	document.getElementById("can").width = viewportwidth - (.2 * viewportwidth);
	document.getElementById("can").height = viewportwidth - (.2 * viewportwidth);

The function drawPresent draws 2500 (50 * 50) squares on the canvas. For each square there is a random colour mixed with Math.round(Math.random() * 255). I added the 1 pixel to the width, because when testing this, i saw white lines between the squares.

function drawPresent() {
	var canvas = document.getElementById('can');
	var ctx = canvas.getContext('2d');

	var ctxwidth = canvas.width;
	var I_width = ctxwidth / 50;

	for(var i=0;i<50;i++){
		for(var j=0;j<50;j++){
			var x = j * I_width;
			var y = i * I_width;

			var rgb1 = Math.round(Math.random() * 255);
			var rgb2 = Math.round(Math.random() * 255);
			var rgb3 = Math.round(Math.random() * 255);
			ctx.fillStyle = 'rgb(' + rgb1 + ',' + rgb2 + ',' + rgb3 + ')';
			ctx.fillRect(x, y, I_width + 1, I_width + 1);

The following code implements these functions in a resize and a load handler. I did need to set the ready and resize functions inside a jQuery(function($)) function. I found this in the fifth part of this post 5 Tips For Using jQuery with WordPress.

jQuery(function ($) {

$(window).resize(function () {
	setInterval(drawPresent, 1000);

$(document).ready(function () {
	setInterval(drawPresent, 1000);


I did decide to not use the library CreateJS for the time being. I did use this in the final presents i made on It is a way for people who are used to Flash to make canvas easier to implement. Since i last worked with Flash in 2006, i have forgotten so many things about it, that it felt like needing to learn Flash all over again. So i’d rather stick with jQuery for general things and get into Javascript itself to make presents.

I’m using a canvas tutorial from the Mozilla Developer Network to get the basics covered.

Read more…

Published on April 1, 2015 at 6:00 by